package com.hl.service;


import com.hl.mapper.VerificationCodeMapper;
import com.hl.domain.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Random;

@Service
public class VerificationCodeService {

    @Autowired
    private VerificationCodeMapper verificationCodeMapper;

    // 生成并保存验证码
    public String generateAndSaveCode(String phoneNumber) {
        // 生成 6 位随机验证码
        Random random = new Random();
        String code = String.format("%06d", random.nextInt(1000000));

        // 设置验证码过期时间为 60 秒
        Timestamp expireTime = new Timestamp(System.currentTimeMillis() + 60000);

        // 创建验证码对象并保存到数据库
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setPhoneNumber(phoneNumber);
        verificationCode.setCode(code);
        verificationCode.setExpireTime(expireTime);

        verificationCodeMapper.insertCode(verificationCode);

        return code;
    }

    // 验证验证码
    public boolean verifyCode(String phoneNumber, String inputCode) {
        VerificationCode latestCode = verificationCodeMapper.findLatestCodeByPhoneNumber(phoneNumber);

        // 如果验证码不存在或已过期，返回 false
        if (latestCode == null || latestCode.getExpireTime().before(new Timestamp(System.currentTimeMillis()))) {
            return false;
        }

        // 比对验证码
        return latestCode.getCode().equals(inputCode);
    }
}
